//
//  MSFoodDetailViewSource.m
//  MSJD
//
//  Created by xiangbo on 2018/9/29.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSFoodDetailViewSource.h"
#import "MSNearByDetailView.h"

@interface MSFoodDetailViewSource ()<MSBasePageViewDelegate>

@property (nonatomic, strong)NSArray *identifyArray;
@property (nonatomic,strong)MSFoodDetailData *detailData;
@property (nonatomic,assign)NSInteger pageNum;

@end

@implementation MSFoodDetailViewSource


- (void)refreshPageData{
    // FIXME:数据类型适配，该值是否需要等data的数据请求成功再赋值？
    NSString *title = @"";
    if ([self.data isKindOfClass:[MSFoodDetailData class]]) {
        title = ((MSFoodDetailData *)self.data).itemName;
    } else {
        title = self.data.title;
    }
    self.pageView.topView.titleLabel.text = [MSSafeObject stringInfo:title];
    _WEAKSELF
    [self getDetailInfo:^(BOOL success) {
        if (success) {
            [weakSelf detailSuccess];
        }
    }];
}

- (void)detailSuccess{
    self.pageView.data = self.detailData;
    [self.pageView.dataArray removeAllObjects];
    for (int i = 0; i < 3; i++) {
        [self.pageView.dataArray addObject:[NSMutableArray array]];
    }
    NSMutableArray *firstSectionArray = self.pageView.dataArray.firstObject;
    MSFoodDetailData *headData = [self.detailData modelCopy];
    headData.height = [MSFoodIntroDetailView headDetailViewHeight];
    [firstSectionArray addObject:headData];
    
    MSFoodDetailData *photosData = [self.detailData modelCopy];
    photosData.height = photosData.photos.count > 0 ? 177.f : 0;
    [firstSectionArray addObject:photosData];
    
    if ([UserAccesser userId].length == 0) {
        _WEAKSELF
        [MSCollectionManager checkIsCollected:self.detailData.mId.stringValue completion:^(BOOL isCollected) {
            weakSelf.pageView.topView.collectButton.selected = isCollected;
        }];
    }else{
        self.pageView.topView.collectButton.selected = [self.detailData.favor boolValue];
    }
    
    MSFoodDetailData *moreData = [self.detailData modelCopy];
    [firstSectionArray addObject:moreData];
    
    [self.pageView.tableview reloadData];
    
//    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getCommentList)];
//    footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
//    self.pageView.tableview.mj_footer = footer;
    [self getNearbyDetailInfo];
}

- (void)getNearbyDetailInfo{
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [self getCommentList:^(MSCommentlistData *commentList) {
        if (commentList.rows > 0  && self.pageView.dataArray.count > 1) {
            NSMutableArray *commentsArray = self.pageView.dataArray[1];
            [commentsArray addObjectsFromArray:commentList.rows];\
        }
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [self getNearbySuggest:^(MSFoodNearbyData *nearbyData) {
        if (nearbyData.rows > 0 && self.pageView.dataArray.count > 2) {
            NSMutableArray *nearByArray = self.pageView.dataArray[2];
            [nearByArray addObjectsFromArray:nearbyData.rows];
        }
        dispatch_group_leave(group);
    }];
    
    _WEAKSELF
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [weakSelf.pageView.tableview reloadData];
    });
}

- (void)getDetailInfo:(void(^)(BOOL success))competion{
    _WEAKSELF
    [MSRequestClient GET:@"v1/item/detail" parameters:@{@"id":self.data.mId.stringValue ?: @"",@"uid":[UserAccesser userId]} responseClassType:MSFoodDetailResponse.class success:^(id responseObject) {
        if (responseObject) {
            weakSelf.detailData = ((MSFoodDetailResponse *)responseObject).data;
            if (competion) {
                competion(YES);
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)getCommentList:(void(^)(MSCommentlistData * commentList))competion{
    _WEAKSELF
    NSDictionary *params = @{@"id":self.data.mId.stringValue ?: @"",@"page" : @(self.pageNum +1)};
    [MSRequestClient GET:@"v1/comment/list" parameters:params responseClassType:MSCommentlistResponse.class success:^(id responseObject) {
        MSCommentlistResponse *commentData = (MSCommentlistResponse *)responseObject;
        if (commentData.data.rows > 0) {
            weakSelf.pageNum += 1;
        }
        if (competion) {
            competion(commentData.data);
        }
    } failure:^(NSError *error) {
        if (competion) {
            competion(nil);
        }
    }];
}

- (void)getNearbySuggest:(void(^)(MSFoodNearbyData *nearbyData))competion{
    CGFloat lon = [UserAccesser longitudeValue];
    CGFloat lat = [UserAccesser latitudeValue];
    NSDictionary *params = @{@"kid":self.data.mId.stringValue ?: @"",@"lon" : @(lon) ?: @"",@"lat" : @(lat) ?: @""};
    [MSRequestClient GET:@"v1/search/nearby" parameters:params responseClassType:MSFoodNearbyResponse.class success:^(id responseObject) {
        MSFoodNearbyResponse *nearbyData = (MSFoodNearbyResponse *)responseObject;
        if (competion) {
            competion(nearbyData.data);
        }
    } failure:^(NSError *error) {
        if (competion) {
            competion(nil);
        }
    }];
    
}

#pragma mark -MSBasePageViewDelegate
- (NSString*)identifier:(id)data indexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return self.identifyArray[indexPath.row];
    }else if (indexPath.section == 1) {
        return NSStringFromClass(MSCommentView.class) ;
    }
    return NSStringFromClass(MSNearByDetailView.class) ;
}

#pragma mark -Property
- (MSFoodDetailPageView *)pageView{
    if (!_pageView) {
        _pageView = [[MSFoodDetailPageView alloc] init];
        _pageView.delegate = self;
        for (NSString *identify in self.identifyArray) {
            [_pageView registetDetailView:identify identifier:identify];
        }
    }
    return _pageView;
}


- (NSArray *)identifyArray{
    if (!_identifyArray) {
        _identifyArray = @[NSStringFromClass(MSFoodIntroDetailView.class),NSStringFromClass(MSFoodPhotosView.class),NSStringFromClass(MSFoodLoactionView.class),NSStringFromClass(MSCommentView.class),NSStringFromClass(MSNearByDetailView.class)];
    }
    return _identifyArray;
}
@end
